<template>
  <div class="supplier-check setting-content">
    <h2 class="setting-header">
      <strong>
        <span>项目管理</span>
      </strong>
    </h2>
    <el-tabs v-model="queryData.state" class="demo-tabs" @tab-change="handleTabChange">
      <el-tab-pane :label="item.label" :name="item.value" v-for="(item, index) in tabsOptions" :key="index"></el-tab-pane>
    </el-tabs>
    <div class="top-btns">
      <el-button type="primary" style="margin: 10px 0" @click="handleGoDetails(null, 1)">快速立项</el-button>
      <SearchCmp style="margin: 10px 0;" v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="handleSearch" />
    </div>

    <div class="list-container">
      <RuifoxTable :loading="tableLoading" :default-index="true" :default-checkbox="true" v-model:tableData="tableData" v-model:fieldList="fieldList">
        <!-- 多选 -->
        <template #default-checkbox="{element}">
          <div class="table-div-check">
            <el-checkbox class="unmover" v-model="element.checked" @change="handleCheckTable(element.id)" size />
          </div>
        </template>
        <template #state="{element}">
          <el-tag type="info" v-if="element.state == 0">立项暂存</el-tag>
          <el-tag type="warning" v-if="element.state == 1">待审核</el-tag>
          <el-tag type="success" v-if="element.state == 2">审核通过</el-tag>
          <el-tag type="danger" v-if="element.state == 3">已驳回</el-tag>
          <el-tag type="info" v-if="element.state == 4">已作废</el-tag>
        </template>
        <template #options="{element}">
          <div class="table-td-option unmover">
            <el-button type="primary" link @click="handleGoDetails(element.id, 1)">查看</el-button>
            <el-dropdown>
              <span class="el-dropdown-link unmover">
                <i class="iconfont">&#xe78d;</i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="element.state == 1" @click="handleGoDetails(element.id, 2)">审核</el-dropdown-item>
                  <el-dropdown-item v-if="![0, 4].includes(element.state)" @click="handleEdit('state', 4, element)">作废</el-dropdown-item>
                  <el-dropdown-item v-if="element.state == 4" link @click="handleEdit('state', 0, element)">恢复</el-dropdown-item>

                  <el-dropdown-item v-if="element.state == 2" link @click="handleGoDetails(element.id, 1, element.step)">
                    <span v-if="element.step == 1">立项</span>
                    <span v-if="element.step == 2">报名审核</span>
                    <span v-if="element.step == 3">报名筛选</span>
                    <span v-if="element.step == 4">数据导出</span>
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleEditBaseInfo(element)">修改截止时间</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </RuifoxTable>

      <PaginationView :total="queryData.total" :pageSize="queryData.pageSize" :currentPage="queryData.currentPage" :allChoose="isAllChooseBtn" :pageChoose="isPageChooseBtn" :checkedNum="checkedNum" @changeSize="handleSizeChange" @currentChange="handleCurrentChange" @changePageChoose="handlePageChoose" @changeAllChoose="handleAllChoose" @invertChoose="handleInvertChoose" @refreshList="getTableData" />
    </div>

    <!-- 添加修改截止时间弹框 -->
    <el-dialog
      v-model="dialogVisible"
      title="修改项目截止时间"
      width="500px"
      :before-close="handleClose"
    >
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="项目截止时间">
          <el-date-picker
            v-model="editForm.projectEndTime"
            type="datetime"
            placeholder="选择截止时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { biddingProjectList, projectUpdateState, editProjectBaseInfo, getPlanOptions } from '@/api/bidding'
// import { fileSecretKey } from '@/views/formSystem/formDesign/config/formCmpConfig.js'
import { tableList as mixTable } from '@ruifox-cms/utils'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  getTableData,
  handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
} = mixTable({
  getListApi: biddingProjectList,
  batchFuncTip: '是否确定删除选中项？',
})

const router = useRouter()
const route = useRoute()
const defaultQueryData = {
  keyWords: '',
  state: -1, //-1 全部 0 立项暂存 1 待审核 2 审核通过 3 审核驳回 4 已作废
  planId: null, //计划id
}
Object.assign(queryData, structuredClone(defaultQueryData))
const handleTabChange = () => {
  setTimeout(() => {
    handleSearch()
  }, 0)
}
const tabsOptions = ref([
  {
    label: '全部',
    value: -1,
  },
  {
    label: '待审核',
    value: 1,
  },
  {
    label: '已通过',
    value: 2,
  },
  {
    label: '未通过',
    value: 3,
  },
  {
    label: '已作废',
    value: 4,
  },
  {
    label: '暂存',
    value: 0,
  },
])
const fieldList = ref([
  {
    title: '项目单号',
    name: 'number',
  },
  {
    title: '项目名称',
    name: 'name',
  },
  {
    title: '报名截止时间',
    name: 'endTime',
  },
  // {
  //   title: '项目地点',
  //   name: 'tenderAddress',
  // },
  {
    title: '项目状态',
    name: 'state',
  },
  {
    title: '操作',
    width: 240,
    fixed: 'right',
    name: 'options',
  },
])

// 获取可选计划字典
const getPlanOptionsAsync = async () => {
  const res = await getPlanOptions()
  searchCmpArray.value[0].options = res.data.map(item => ({
    label: item.name,
    value: item.id,
  }))
  if (route.query.id) {
    queryData.planId = Number(route.query.id)
  }
  handleSearch()
}
getPlanOptionsAsync()
const searchCmpArray = ref([
  { label: '计划筛选', key: 'planId', form_type: 'select', options: [] },
  { label: '关键词', key: 'keyWords' },
])
const handleGoDetails = (id, pageType, step) => {
  router.push({
    path: '/bidding/project/approval',
    query: {
      id,
      pageType,
      step,
    },
  })
}
const handleEdit = (field, val, row) => {
  ElMessageBox.confirm(`<div><p style="font-size: 16px;margin-bottom: 15px;">是否确认操作？</p></div>`, '操作确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    //listAction是否列表操作 1 是 0 否
    let params = structuredClone(row)
    params[field] = val
    let res = await projectUpdateState({id: row.id, state: val})
    handleSearch()
    if (res.code === 20000) {
      ElMessage({
        message: '操作成功',
        type: 'success',
      })
    }
  })
}

// 添加弹框相关的响应式变量
const dialogVisible = ref(false)
const editForm = ref({
  id: null,
  projectEndTime: ''
})

// 打开弹框
const handleEditBaseInfo = (row) => {
  editForm.value.id = row.id
  editForm.value.projectEndTime = row.projectEndTime
  dialogVisible.value = true
}

// 关闭弹框
const handleClose = () => {
  dialogVisible.value = false
  editForm.value = {
    id: null,
    projectEndTime: ''
  }
}

// 提交修改
const handleSubmit = async () => {
  try {
    await editProjectBaseInfo({
      id: editForm.value.id,
      projectEndTime: editForm.value.projectEndTime
    })
    ElMessage({
      type: 'success',
      message: '修改成功'
    })
    handleClose()
    handleSearch() // 刷新表格数据
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '修改失败'
    })
  }
}
</script>
<style lang="scss" scoped>
.top-btns {
  display: flex;
  align-items: flex-start;
  gap: 0 10px;
}
header {
  margin-bottom: 20px;
  overflow: hidden;
  .left-btn {
    float: left;
    display: flex;
    align-items: center;
  }
  .right-btn {
    float: right;
    display: flex;
    align-items: center;
    .keyWords-search {
      width: 320px;
      margin-right: 20px;
      i {
        cursor: pointer;
        color: $mainColor;
      }
    }
    .el-btn2 {
      .search-icon {
        color: $mainColor;
      }
      span {
        margin-left: 5px;
        color: $black;
      }
      .active-focus {
        color: $mainColor;
      }
    }
    .el-btn1 {
      width: 111px;
      height: 32px;
      .tuo-icon {
        color: $mainColor;
        font-size: 16px;
      }
      span {
        margin-left: 5px;
        color: $black;
      }
      .active-focus {
        color: $mainColor;
      }
    }
    .change-card {
      height: 32px;
      width: 64px;
      box-sizing: border-box;
      border: var(--el-border);
      border-radius: 4px;
      display: flex;
      overflow: hidden;
      margin-left: 20px;
      a {
        display: flex;
        width: 50%;
        height: 100%;
        align-items: center;
        justify-content: center;
      }
      a.active {
        background-color: $mainColor;
        i {
          color: #fff;
        }
      }
    }
  }
}
.ruifox-table tbody tr {
  cursor: auto;
  td {
    p {
      @include textEllipsis(16px, 1);
    }
    a {
      color: $mainColor;
      @include textEllipsis(16px, 1);
      &:hover {
        text-decoration: underline;
      }
    }
  }
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>